//进程等待  wait   waitpid 练习

#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<stdlib.h>



int main()
{
  pid_t id=fork();
  
  if(id==0)
  {
    int cnt=10;
    while(cnt)
    {
      printf("i am child process\n");
      sleep(1);
      cnt--;
    }
    exit(107);
  }

  while(1)
  {
    int status =0;

    pid_t ret_id =waitpid(id,&status,WNOHANG);

    if(ret_id<0)
    {
      printf("等待错误");
      exit(-1);
    }

    else if(id == 0)
    {
      printf("child\n");
      sleep(2);
      continue;
    }
    else 
    {
      if(WIFEXITED(status))
      {
        
        printf("等待成功，子进程退出码：%d\n",WEXITSTATUS(status));
      }
      else 
      {
        printf("等待成功，子进程退出信号：%d\n",status & 0x7F);
      }
      

  printf("进程退出成功，pid%d,ppid:%d,ret_id:%d,child exit code:%d,child exit signal:%d\n"
      ,getpid(),getppid(),ret_id,(status>>8)&0xFF,status & 0x7F);

      break;
    

    }



  }








  return 0;
}
